﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

struct MessageStruct
{
    public MessageStruct(string mes, Vector4 color)
    {
        m_Message = mes;
        m_Color = color;
    }
    public string m_Message;
    public Vector4 m_Color;
}
class MessageShow
{
    public static MessageShow Instance = new MessageShow();

    public CallbackString OnMessageCallback;

    public List<MessageStruct> m_ShowMessageList = new List<MessageStruct>();
    float m_TimeCount=0;

    public void Update()
    {
        float timeMax = 0.4f;
        m_TimeCount += Time.deltaTime;
        if (m_ShowMessageList.Count > 0 && m_TimeCount > timeMax)
        {
            MessageStruct mstr = m_ShowMessageList[0];
            Messaage(mstr.m_Message, mstr.m_Color);
            m_ShowMessageList.Remove(mstr);
            m_TimeCount = 0;
        }
    }

    /// <summary>
    ///     显示一个提示信息，在屏幕中央
    /// </summary>
    /// <param name="message"></param>
    public void Messaage(string message)
    {
        Messaage(message, Vector4.one);
    }
    public void Warning(string message)
    { 
        Messaage(message, new Vector4(0.8f, 0.7f, 0.1f, 1));
        Debug.LogWarning(message);
    }
    public void Error(string message)
    {
        Messaage(message, new Vector4(1,0,0,1));
        Debug.LogWarning(message);
    }
    public void Messaage(string message, Vector4 color, bool append = false)
    {
        if(append)
        {
            m_ShowMessageList.Add(new MessageStruct(message, color));
            return;
        }
        Canvas parent = GameObject.FindObjectOfType<Canvas>();
        if (parent)
        {
            GameObject obj = new GameObject();
            obj.transform.SetParent(parent.transform);

            RectTransform rect = obj.AddComponent<RectTransform>();
            rect.sizeDelta = new Vector2(Screen.width, 80);
            rect.localScale = new Vector3(1, 1, 1);
            Text text = obj.AddComponent<Text>();
            text.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
            text.alignment = TextAnchor.MiddleCenter;
            text.raycastTarget = false;
            text.fontSize = 40;
            text.color = color;
            Message message2 = obj.AddComponent<Message>();

            message2.Text = message;
        }
        if (OnMessageCallback != null)
            OnMessageCallback(message);
    }
}